/**
 * JAVACC DEMO 1.0
 */
package com.apache.uct.service.plugins;

import com.apache.api.manager.PluginConnector;
import com.apache.api.vo.ParamsVo;
import com.apache.api.vo.ResultEntity;
import com.apache.database.constant.Validator;
import com.apache.database.db.IDao;
import com.apache.database.model.MethodParam;
import com.apache.uct.common.entity.*;
import com.apache.uct.manager.ActGiveManager;
import com.apache.uct.manager.RoleGiveManager;
import com.apache.uct.manager.RoleManager;
import org.apache.log4j.Logger;

import java.util.List;

/**
 * description:  授予用户权限或取消权限
 *
 * @author iussoft 创建时间：2016-3-26
 */
public class GrantActToUserPlugin implements PluginConnector {

    private Logger log = Logger.getLogger(GrantActToUserPlugin.class);

    private IDao userDao;

    private IDao actDao;

    private ActGiveManager actGiveManager;

    private RoleGiveManager roleGiveManager;

    private RoleManager roleManager;

    /**
     * TODO 授予用户权限或取消权限.  <br>
     * 参数说明:<br>
     * doAdd:执行添加或取消标记(必须参数:true/false)<br>
     * userId:被授权用户ID;
     * userEname:被授权用户账号<br>
     * roleId:角色ID或roleEname:角色标识   授予用户指定角色<br>
     * actId:权限ID或fullEname:权限英文全称  授予用户指定权限<br>
     */
    public Object execute(ParamsVo vo) throws Exception {
        ResultEntity result = new ResultEntity();
        try {
            result.setResult("true");
            String doAdd = String.valueOf(vo.getParams("doAdd"));//执行添加或取消标记(必须参数:true/false)
            if (Validator.isNull(doAdd)) {
                result.setMessage("方法参数为空或操作失败");
            }
            String userId = String.valueOf(vo.getParams("userId"));
            String userEname = String.valueOf(vo.getParams("userEname"));
            User user = getUserByUserIdOrUserEname(userId, userEname);
            if (Validator.isEmpty(user)) {
                result.setMessage("用户唯一标识参数未传递或查询的用户对象不存在");
                return result;
            }
            String roleId = String.valueOf(vo.getParams("roleId"));
            String roleEname = String.valueOf(vo.getParams("roleEname"));
            if ("true".equalsIgnoreCase(doAdd)) {//授权
                result.setMessage(addAct(vo, user, roleId, roleEname));
            } else if ("false".equalsIgnoreCase(doAdd)) {//取消权限
                result.setMessage(delAct(vo, user, roleId));
            } else {
                result.setMessage("方法参数不正确");
            }
            if ("授权成功".equals(result.getMessage()) || "剥夺权限成功".equals(result.getMessage())) {
                result.setEntity("true");
            } else {
                result.setEntity("false");
            }
        } catch (Exception e) {
            result.setResult("true");
            log.error("执行机构查询失败 ", e);
            result.setMessage("机构查询失败！");
        }
        return result;
    }

    //授予用户权限
    private String addAct(ParamsVo vo, User user, String roleId, String roleEname) {
        if (Validator.isNotNull(roleId) || Validator.isNotNull(roleEname)) {//授角色权限
            Role role = getRoleByRoleId(roleId, roleEname);
            if (!Validator.isEmpty(role)) {
                RoleGive rg = new RoleGive();
                rg.setUserId(user.getUserId());
                rg.setRoleId(role.getRoleId());//151125
                rg.setRoleEname(role.getRoleEname());
                rg.setUserEname(user.getUserEname());
                ParamsVo<RoleGive> gvo = new ParamsVo<RoleGive>();
                gvo.setObj(rg);
                roleGiveManager.saveInfo(gvo);
            }
            return "授权成功";
        } else {
            String actId = String.valueOf(vo.getParams("actId"));
            String actEname = String.valueOf(vo.getParams("actEname"));
            String fullEname = String.valueOf(vo.getParams("fullEname"));
            String actIds = String.valueOf(vo.getParams("actIds"));
            if (Validator.isNotNull(actIds)) {
                String ids[] = actIds.split(",");
                for (int i = 0; i < ids.length; i++) {
                    if (Validator.isNull(ids[i]))
                        continue;
                    actId = ids[i];
                    buildUserAct(actId, "", "", user);
                }
                return "授权成功";
            } else {
                return buildUserAct(actId, actEname, fullEname, user);
            }
        }
    }

    private String buildUserAct(String actId, String actEname, String fullEname, User user) {
        Act act = getActByAttr(actId, actEname, fullEname);
        if (null == act)
            return "权限的唯一标识未传递或权限不存在,操作失败";
        List<ActGive> list = getActGives(user.getUserId(), act.getActId());
        if (!Validator.isEmpty(list)) {//该用户已经存在改权限
            return "该用户已经拥有该权限,无需再次授权";
        } else {//不存在该权限时
            ParamsVo<ActGive> avo = new ParamsVo<ActGive>();
            ActGive actGive = new ActGive();
            actGive.setGiveType("user");
            actGive.setActId(act.getActId());
            actGive.setRoleId(user.getUserId());
            actGive.setRoleEname(user.getUserEname());
            actGive.setCreateTime(System.currentTimeMillis());
            actGive.setActFullEname(act.getFullEname());
            actGive.setSysEname(act.getSysEname());
            avo.setObj(actGive);
            actGiveManager.saveInfo(avo);
            ActCacheHelper.getInstance().writeCache(user.getUserId(), "user", act.getActId(),
                    act.getFullEname() + ";" + act.getActUrl(), true);//删除权限缓存
            return "授权成功";
        }
    }

    //剥夺用户权限
    private String delAct(ParamsVo vo, User user, String roleId) {
        if (Validator.isNotNull(roleId)) {
            RoleGive rg = new RoleGive();
            rg.setUserId(user.getUserId());
            rg.setRoleId(roleId);
            ParamsVo<RoleGive> gvo = new ParamsVo<RoleGive>();
            gvo.setObj(rg);
            roleGiveManager.deleteInfo(gvo);
            return "剥夺权限成功";
        } else {
            String actId = String.valueOf(vo.getParams("actId"));
            String actEname = String.valueOf(vo.getParams("actEname"));
            String fullEname = String.valueOf(vo.getParams("fullEname"));

            String actIds = String.valueOf(vo.getParams("actIds"));
            if (Validator.isNotNull(actIds)) {
                String ids[] = actIds.split(",");
                for (int i = 0; i < ids.length; i++) {
                    if (Validator.isNull(ids[i]))
                        continue;
                    buildDelUserAct(actId, "", "", user);
                }
                return "剥夺权限成功";
            } else {
                return buildDelUserAct(actId, actEname, fullEname, user);
            }
        }
    }

    private String buildDelUserAct(String actId, String actEname, String fullEname, User user) {

        if (Validator.isNull(actId)) {
            Act act = getActByAttr(actId, actEname, fullEname);
            if (null == act)
                return "权限的唯一标识未传递或权限不存在,操作失败";
            actId = act.getActId();
        }
        ParamsVo<ActGive> avo = new ParamsVo<ActGive>();
        ActGive actGive = new ActGive();
        actGive.setActId(actId);//151125
        actGive.setRoleId(user.getUserId());
        actGive.setGiveType("user");
        avo.setObj(actGive);
        actGiveManager.deleteInfo(avo);
        ActCacheHelper.getInstance().writeCache(user.getUserId(), "user", actId, "", false);//删除权限缓存
        return "剥夺权限成功";
    }

    //获取权限信息
    private Act getActByAttr(String actId, String actEname, String fullEname) {
        MethodParam param = new MethodParam("ByActAttr", "", "", Act.class.getName());
        StringBuffer sb = new StringBuffer();
        if (Validator.isNotNull(actEname)) {
            sb.append(" and actEname =:actEname");
            param.setParams("actEname", actEname);
        }
        if (Validator.isNotNull(actId)) {
            sb.append(" and actId =:actId");
            param.setParams("actId", actId);
        }
        if (Validator.isNotNull(fullEname)) {
            sb.append(" and fullEname =:fullEname");
            param.setParams("fullEname", fullEname);
        }
        if (!Validator.isNull(sb.toString())) {
            param.setSqlStr(actDao.getSql(2) + sb.toString());
            return (Act) actDao.selectSingle(param);
        } else {
            return null;
        }
    }

    //获取分配的权限值
    private List<ActGive> getActGives(String userId, String actId) {
        ParamsVo<ActGive> vo = new ParamsVo<ActGive>();
        ActGive ag = new ActGive();
        ag.setActId(actId);
        ag.setRoleId(userId);
        ag.setGiveType("user");
        vo.setObj(ag);
        return actGiveManager.getList(vo);
    }

    //获取角色信息
    private Role getRoleByRoleId(String roleId, String roleEname) {
        if (Validator.isNotNull(roleId)) {
            MethodParam param = new MethodParam("ById", "", "", Role.class.getName());
            param.setInfoId(roleId);
            Role role = (Role) userDao.selectById(param);
            return role;
        } else {
            ParamsVo vo = new ParamsVo();
            Role role = new Role();
            role.setRoleEname(roleEname);
            vo.setObj(role);//1125
            List list = roleManager.getList(vo);
            if (!Validator.isEmpty(list))
                return (Role) list.get(0);
            return null;
        }
    }

    //获取用户信息
    private User getUserByUserIdOrUserEname(String userId, String userEname) {
        MethodParam param = new MethodParam("ByUserAttr", "", "", User.class.getName());
        StringBuffer sb = new StringBuffer();
        if (Validator.isNotNull(userEname)) {
            sb.append(" and userEname =:userEname");
            param.setParams("userEname", userEname);
        }
        if (Validator.isNotNull(userId)) {
            sb.append(" and userId =:userId");
            param.setParams("userId", userId);
        }
        if (!Validator.isNull(sb.toString())) {
            param.setSqlStr(userDao.getSql(2) + sb.toString() + " and userStatus > -1");
            User user = (User) userDao.selectSingle(param);
            return user;
        } else {
            return null;
        }
    }

    public void setRoleGiveManager(RoleGiveManager roleGiveManager) {
        this.roleGiveManager = roleGiveManager;
    }

    public void setActDao(IDao actDao) {
        this.actDao = actDao;
    }

    public void setActGiveManager(ActGiveManager actGiveManager) {
        this.actGiveManager = actGiveManager;
    }

    public void setRoleManager(RoleManager roleManager) {
        this.roleManager = roleManager;
    }

    public void setUserDao(IDao userDao) {
        this.userDao = userDao;
    }
}
